#include "DXPickRay.h"

poly::ray3 DXPickRay::calculatePickRay(int x, int y, poly::D3DDevice Device)
{
	float px = 0;
	float py = 0;
	poly::ray3 ray;

	D3DVIEWPORT9 vp;
	poly::float44 proj;

	Device->GetViewport(&vp);
	Device->GetTransform(D3DTS_PROJECTION, &proj);
	
	px = ((( 2.0f*x) / vp.Width) - 1.0f) / proj(0, 0);
	py = (((-2.0f*y) / vp.Height) + 1.0f) / proj(1, 1);
	
	ray.origin     = poly::float3(0, 0, 0);
	ray.direction  = poly::float3(px, py, 1);

	return ray;
}

poly::ray3 DXPickRay::toWorld(const poly::ray3 &ray, poly::D3DDevice Device)
{
	poly::float44 view;
	Device->GetTransform(D3DTS_VIEW, &view);
	
	poly::float44 viewInv;
	D3DXMatrixInverse(&viewInv, 0, &view);

	poly::ray3 temp = ray;
	transformRay(&temp, &viewInv);

	return temp;
}